package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.net.wifi.ScanResult;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;

public class ApRelevanceTestWidgetProxy extends GeneralTestWidget {

    private WlanManager wlanManager;
    private Handler hander;
    private Handler handlerChild;
    private Activity ctx; 
    // private String mac;
    private static final String TAG = "ApRelevanceTest";
    private Button backBtn;
    private boolean connecting;
    
    private boolean isFirst = true;

    public void setConnecting(boolean connecting) {
        this.connecting = connecting;
    }

    private int current;

    public void setCurrent(int current) {
        this.current += current;
    }

    private int timeout_num;// 超时次数;

    private int frequency;
    private float totalTime = 0f;
    private Task task; 
    public static int testFlag = 0; 
    public static int taskFlag = 0;  

	public ApRelevanceTestWidgetProxy(Activity context, Handler handler) {
        super(context);
        inflate(context, R.layout.aprelevance_test_widget_proxy, this);
        this.ctx = context; 
        this.handlerChild = handler;
        backBtn = (Button) findViewById(R.id.ap_test_proxy_btnback);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });

        hander = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.DO_NEXT_TEST:
                  //  showNextText();
                    break;
                default:
                    update(msg.what);
                }
            }
        };

        wlanManager = new WlanManager(ctx);
        wlanManager.setHandler(hander);
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        frequency = task.testCount;
        start(task.scanResult);

    }
  
    private final class ApTestThread extends Thread {
        private ScanResult scan;

        public ApTestThread(final ScanResult scan) {
            this.scan = scan;
        }

        @Override
        public void run() {
        	executable = true;
            while (current < frequency && executable) {
                if (!connecting) {
                    current++;
                    connecting = true;
                    wlanManager.connect(scan);
                    startConnectTimeoutListener();
                }
            }
        }

    }

    private void start(final ScanResult scan) {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) { 
            final ApTestThread apTestThread = new ApTestThread(scan);
         //   this.showProgressDialog(ctx, "正在进行AP关联测试...", frequency);
            apTestThread.start();
        }
    }

    private void startConnectTimeoutListener() {
        TimerTask wifiReceiverTask = new TimerTask() {
            public void run() {
                if (connecting) {
                    Log.e(TAG, "AP关联第" + current + "测试连接超时");
                    wlanManager.setConnectedConsumeTime(System.currentTimeMillis());
                    wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(wifiReceiverTask, WlanManager.CONNECT_TIMEOUT);
    }

    void update(int what) {
    	//----------------------------------------------------------
			if(isFirst) {
				isFirst = false;
				StringBuffer temp = new StringBuffer();
				GlobalApp.result_AP_test = temp;
			}
		//----------------------------------------------------------
        setDialogProgress(current);
        switch (what) {
        case MessageWhat.WIFI_SUCESS_CONNECTED:
            if (connecting) {
                float costTime = (wlanManager.getConnectedConsumeTime() - wlanManager.getStartConntectTime()) / (float)1000; 
                StringBuffer s = new StringBuffer();
                s.append("第").append(current).append("次关联AP点：");
                s.append(wlanManager.getCurrentScanResult().SSID)
                .append("\n MAC地址：").append(wlanManager.getCurrentScanResult().BSSID);
                s.append("\n IP：").append(wlanManager.getIpAddress())
                .append("  时间：").append(costTime).append(" s");
              //----------------------------------------------------------
                
				GlobalApp.result_AP_test.append("第").append(current).append("次关联AP点：")
						.append(wlanManager.getCurrentScanResult().SSID)
						.append("\nMAC地址：").append(wlanManager.getCurrentScanResult().BSSID)
						.append("\nIP：").append(wlanManager.getIpAddress())
						.append("\n时间：").append(costTime).append(" s\n");
				
			//----------------------------------------------------------
                
                totalTime += costTime; 
                if (current == frequency) {
                    wlanManager.sendMsg(MessageWhat.DONE);
                }
                connecting = false;
            }
            break;
        case MessageWhat.WIFI_CONNECT_TIMEOUT:
            StringBuffer s = new StringBuffer();
            s.append("第").append(current).append("次关联 AP点：");
            s.append(wlanManager.getCurrentScanResult().SSID)
            .append(" MAC地址：").append(wlanManager.getCurrentScanResult().BSSID).append("  失败.");
          //----------------------------------------------------------
            
			GlobalApp.result_AP_test.append("第").append(current).append("次关联 AP点：")
					.append(wlanManager.getCurrentScanResult().SSID)
					.append("\nMAC地址：").append(wlanManager.getCurrentScanResult().BSSID)
					.append("\n失败.\n");
		
		//---------------------------------------------------------- 
            setTimeoutNum(1);
            if (current == frequency) {
                wlanManager.sendMsg(MessageWhat.DONE);
            }
            connecting = false;
            break;
        case MessageWhat.DONE:
            s = new StringBuffer();
            DecimalFormat df = new DecimalFormat("#0.000");
            int success = frequency - timeout_num;
            s.append("关联测试次数：").append(frequency);
            s.append("  关联成功次数：").append(success).append('\n');
            s.append("关联成功率：").append((float) success / frequency * 100).append('%');
            s.append("  关联平均时延：").append(df.format((float) totalTime / frequency)).append('s');
          //----------------------------------------------------------
            
			GlobalApp.result_AP_test.append("\n关联测试次数：").append(frequency)
					.append("\n关联成功次数：").append(success)
					.append("\n关联成功率：").append((float) success / frequency * 100).append('%')
					.append("\n关联平均时延：").append(df.format((float) totalTime / frequency)).append('s');
		
		//---------------------------------------------------------- 

            task.relevanceAPAvgTime = df.format((float) totalTime / frequency);
            if(success>0 && ((float)totalTime / frequency)<0.001){
           	 task.relevanceAPAvgTime = "0.001";
            }
            task.relevanceAPSuccessRate = String.valueOf((float) success / frequency * 100);
            
            task.apTestCount = task.testCount +"";
            success = success<0 ? 0:success;
            task.apTestSuccessCount = success +"";
            

System.out.println("task.apTestCount => " + task.apTestCount);
System.out.println("task.apTestSuccessCount => " + task.apTestSuccessCount);
System.out.println("task.relevanceAPSuccessRate => " + task.relevanceAPSuccessRate);
System.out.println("task.relevanceAPAvgTime => " + task.relevanceAPAvgTime);
            
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);
            this.dismissProgressDialog(); 
            connecting = false; 
            handlerSendToTarget(handlerChild, MessageWhat.HANDLER_APREL);
            break;
        } 

    } 
    private void setTimeoutNum(int timeout_num) {
        this.timeout_num += timeout_num;
    } 

}
